/**
 * Created with WebStorm.
 * Author: qiang.niu(http://www.siptea.cn)
 * Date: 2015/7/6 11:35
 * 注意，Amap.WalkingRender与Amap.DrivingRender的代码完全一样
 */
if (typeof(Lib) == "undefined") {
	Lib = {};
}
Lib.AMap = Lib.AMap || {};
Lib.AMap.WalkingRender = function() {
	var me = this;
	//me.author="qiang.niu(http://www.siptea.cn)";
	me._currentRouteTitle = null; //当前打开的驾车方案标题div
	me._currentRouteOptenitem = null; //当前打开的驾车方案内容div
	/**
	 * 自动渲染
	 * @method Lib.AMap.DrivingRender#autoRender
	 * @param {object} [options] options
	 * @param {AMap.Map} [options.map] 高德js api的map对象
	 * @param {HTMLElement|String} [options.panel] html的dom节点或其id号
	 */
	me.autoRender = function(options) { //options.map otpions.panel options.data
			me.clear();
			if (!options || !options.data || (!options.panel && !options.map)) {
				return;
			}
			options.data.start = options.data.start || {
				location: options.data.origin,
				name: "起点"
			};
			options.data.end = options.data.end || {
				location: options.data.destination,
				name: "终点"
			};
			options.data.start.type = "start";
			options.data.end.type = "end";
			this.options = options; //保存用户输入的参数
			this.hideMarkers = options['hideMarkers'] || false;
			if (options.map) {
				this._infoWindow = new AMap.InfoWindow({ //点的信息窗体
					size: new AMap.Size(0, 0),
					isCustom: true,
					offset: new AMap.Pixel(0, -30)
				});
				this._overlays = []; //线路
				this._route = []; //鼠标划过驾车方案时绘制的半透明线
				this._highlightOverlay = null; //高亮线路
				if (!options.panel) { //如果传入了panel,在生成panel时会默认绘制第一个驾车方案，所以在这里就不绘制了
					this.drawRouteOverlays(0); //默认绘制第一个驾车方案
				}
			}
			if (options.panel) {
				if (Object.prototype.toString.call(options.panel) == '[object String]') {
					options.panel = document.getElementById(options.panel);
				}
				options.panel.innerHTML = this.view.createPanel(options.data);
				this.enableListeners();
			}
		}
		/**
		 * 清空面板和地图
		 * @method Lib.AMap.DrivingRender#clear
		 */
	me.clear = function() {
		this.clearPanel();
		this.clearOverlays();
	};
	/**
	 * 绘制某个驾车方案的线路图（只画起始点到结束点之间的半透明线）
	 * @method Lib.AMap.DrivingRender#drawRoute
	 * @param index  驾车方案索引号
	 */
	me.drawRoute = function(index) {
			var data = this.options.data,
				route = data.routes[index];
			var distance = route.distance,
				steps = route.steps;
			var walkPaths = [],
				busPaths = [],
				railwayPaths = [];
			walkPaths.push([data.start.location, steps[0].path[0]]);
			var lastStepPath = steps[steps.length - 1].path
			walkPaths.push([lastStepPath[lastStepPath.length - 1], data.end.location]);
			for (var i = 0, step; i < steps.length; i++) {
				step = steps[i];
				//busPaths.push(step.path);
				busPaths = busPaths.concat(step.path);
			}
			if (busPaths.length > 0) {
				busPaths = [busPaths];
			}
			this.clearRoute();
			this._route = this.addOverlays([], walkPaths, busPaths, railwayPaths, {
				strokeOpacity: 0.4
			});
		}
		/**
		 *  清空某个驾车方案的线路图（只画起始点到结束点之间的半透明线）
		 *  @method Lib.AMap.DrivingRender#clearRoute
		 */
	me.clearRoute = function() {
			if (this._route) {
				for (var i = 0; i < this._route.length; i++) {
					this._route[i].setMap(null);
				}
				this._route = [];
			}
		}
		/**
		 * 绘制某个驾车方案的线路图
		 * @method Lib.AMap.DrivingRender#drawRouteOverlays
		 * @param index 驾车方案索引号
		 */
	me.drawRouteOverlays = function(index) {
			var data = this.options.data,
				route = data.routes[index];
			var distance = route.distance,
				steps = route.steps;
			var walkPaths = [],
				busPaths = [],
				points = [],
				railwayPaths = [];
			points.push(data.start);
			points.push(data.end);
			walkPaths.push([data.start.location, steps[0].path[0]]);
			var lastStepPath = steps[steps.length - 1].path
			walkPaths.push([lastStepPath[lastStepPath.length - 1], data.end.location]);
			for (var i = 0, step; i < steps.length; i++) {
				step = steps[i];
				//busPaths.push(step.path);
				busPaths = busPaths.concat(step.path);
			}
			if (busPaths.length > 0) {
				busPaths = [busPaths];
			}
			this.clearOverlays();
			this._overlays = this.addOverlays(points, walkPaths, busPaths, railwayPaths);
			me.options.map.setFitView(this._overlays);
		}
		/**
		 * 添加地图覆盖物
		 * @method Lib.AMap.DrivingRender#addOverlays
		 * @param points  点
		 * @param walkPaths  步行线
		 * @param busPaths  公交和地铁线
		 * @param railwayPaths 铁路线
		 * @param styleOptions 样式
		 * @returns {Array}
		 */
	me.addOverlays = function(points, walkPaths, busPaths, railwayPaths, styleOptions) {
			var map = this.options.map;
			styleOptions = styleOptions || {
				strokeOpacity: 1
			}
			var _overlays = [];
			if (!this.hideMarkers) {
				if (points[0]) {
					//绘制起点
					var start = new AMap.Marker({
						map: map,
						position: points[0].location, //基点位置
						content: '<div class="amap-lib-marker-from"></div>'
					});
					start.isOfficial = true;
					start._data = points[0];
					AMap.event.addListener(start, "click", this.listener.markerClick);
					_overlays.push(start);
				}
				if (points.length > 1) {
					//绘制终点
					var end = new AMap.Marker({
						map: map,
						position: points[points.length - 1].location, //基点位置
						content: '<div class="amap-lib-marker-to"></div>'
					});
					end.isOfficial = true;
					end._data = points[points.length - 1];
					AMap.event.addListener(end, "click", this.listener.markerClick);
					_overlays.push(end);
				}

				for (var i = 1, point; i < points.length - 1; i++) { //绘制途经点
					var transit_mode = points[i].segment.transit_mode.toLowerCase();
					point = new AMap.Marker({
						map: map,
						position: points[i].location, //基点位置
						content: '<div class="amap-lib-marker-stop amap-lib-marker-bus-' + transit_mode + 'Stop"></div>',
						offset: {
							x: -12,
							y: -12
						} //相对于基点的位置
					});
					point.isOfficial = true;
					point._data = points[i];
					AMap.event.addListener(point, "click", this.listener.markerClick);
					_overlays.push(point);
				}
			if (points[0]) {
				//绘制起点
				var start = new AMap.Marker({
					map: map,
					position: points[0].location, //基点位置
					content: '<div class="amap-lib-marker-from"></div>'
				});
				start.isOfficial = true;
				start._data = points[0];
				AMap.event.addListener(start, "click", this.listener.markerClick);
				_overlays.push(start);
			}
			if (points.length > 1) {
				//绘制终点
				var end = new AMap.Marker({
					map: map,
					position: points[points.length - 1].location, //基点位置
					content: '<div class="amap-lib-marker-to"></div>'
				});
				end.isOfficial = true;
				end._data = points[points.length - 1];
				AMap.event.addListener(end, "click", this.listener.markerClick);
				_overlays.push(end);
			}

			for (var i = 1, point; i < points.length - 1; i++) { //绘制途经点
				var transit_mode = points[i].segment.transit_mode.toLowerCase();
				point = new AMap.Marker({
					map: map,
					position: points[i].location, //基点位置
					content: '<div class="amap-lib-marker-stop amap-lib-marker-bus-' + transit_mode + 'Stop"></div>',
					offset: {
						x: -12,
						y: -12
					} //相对于基点的位置
				});
				point.isOfficial = true;
				point._data = points[i];
				AMap.event.addListener(point, "click", this.listener.markerClick);
				_overlays.push(point);
			}
			}
			//绘制乘车的路线
			for (var i = 0, busPath; i < busPaths.length; i++) {
				busPath = new AMap.Polyline({
					map: map,
					path: busPaths[i],
					lineJoin: 'round',
					strokeColor: "#09f", //线颜色
                    strokeOpacity : 0.8,
                    strokeWeight : 6
				});
				busPath.isOfficial = true;
				_overlays.push(busPath);
			}
			//绘制火车发站与到站之间的线
			for (var i = 0, railwayPath; i < railwayPaths.length; i++) {
				railwayPath = new AMap.Polyline({
					map: map,
					path: railwayPaths[i],
					strokeColor: "gray", //线颜色
					strokeStyle: "dashed",
					strokeOpacity: styleOptions.strokeOpacity, //线透明度
					strokeWeight: 4 //线宽
				});
				railwayPath.isOfficial = true;
				_overlays.push(railwayPath);
			}
			//绘制步行的路线
			for (var i = 0, walkPath; i < walkPaths.length; i++) {
				walkPath = new AMap.Polyline({
					map: map,
					path: walkPaths[i],
					strokeColor: "gray", //线颜色
					strokeStyle: "dashed",
					strokeOpacity: styleOptions.strokeOpacity, //线透明度
					strokeWeight: 6 //线宽
				});
				walkPath.isOfficial = true;
				_overlays.push(walkPath);
			}
			return _overlays;
		}
		/**
		 * 清空面板
		 *  @method Lib.AMap.DrivingRender#clearPanel
		 */
	me.clearPanel = function() {
			if (this.options && this.options.panel) {
				this.options.panel.innerHTML = '';
			}
		}
		/**
		 * 清空绘制的地图覆盖物
		 * @method Lib.AMap.DrivingRender#clearOverlays
		 */
	me.clearOverlays = function() {
			if (this._overlays) {
				for (var i = 0, overlay; i < this._overlays.length; i++) {
					overlay = this._overlays[i];
					overlay.setMap(null);
				}
				this._overlays = [];
			}
			if (this._infoWindow) {
				this._infoWindow.close();
			}
			if (this._highlightOverlay) {
				this._highlightOverlay.setMap(null);
				this._highlightOverlay = null;
			}
			this.clearRoute();
		}
		/**
		 * 解析出标题
		 * @method Lib.AMap.DrivingRender#getTitle
		 * @param route
		 * @returns {string}
		 */
	me.getTitle = function(route) { //
			var policy = route.policy ? " | <span class='blue'>" + route.policy + "</span>" : "";
			var result = me.util.getTime(route.time) + "(" + me.util.getDistance(route.distance) + ")" + policy;
			return result;
		}
		/**
		 * 工具类
		 * @name util
		 * @type {object}
		 * @memberof Lib.AMap.DrivingRender#
		 */
	me.util = {};
	me.util.getDistance = function(len) { //距离，米换算为千米
		if (len <= 1000) {
			var s = len;
			return s + "米";
		} else {
			var s = Math.round(len / 10);
			return "" + s / 100 + "公里";
		}
	}
	me.util.getTime = function(second) { //距离，米换算为千米
		var minute = (second / 60).toFixed(0);
		if (minute < 60) {
			return "" + minute + "分钟";
		} else {
			return "" + Math.floor(minute / 60) + "小时" + (minute % 60) + "分钟";
		}
	}
	me.util.domstr2dom = function(arg) {
		var objE = document.createElement("div");
		objE.innerHTML = arg;
		return objE;
	}

	/*
	 * 根据类名获得元素
	 * @method getElementsByClassName
	 * @memberof Lib.AMap.DrivingRender#util#
	 * @param className  类名
	 * @param tag [tag='*']   元素名 默认所有元素
	 * @param parent [parent=document]   父元素 默认doucment
	 * @returns {Array}
	 */
	me.util.getElementsByClassName = function(className, tag, parent) {
			var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
			//var testClass = new RegExp("(\w|\s)*" + className + "(\w|\s)*");
			var tag = tag || "*";
			var parent = parent || document;
			var elements = parent.getElementsByTagName(tag);
			var returnElements = [];
			for (var i = 0, current; i < elements.length; i++) {
				current = elements[i];
				if (testClass.test(current.className)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		}

		/**
		 * 监听类
		 * @name listener
		 * @type {object}
		 * @memberof Lib.AMap.DrivingRender#
		 */
	me.listener = {};
	me.listener.markerClick = function() {
		var data = this._data;

		if (data.type == 'start' || data.type == 'end') {
			me._infoWindow.setOffset(new AMap.Pixel(0, -30));
		} else {
			me._infoWindow.setOffset(new AMap.Pixel(0, 0));
		}
		if (data.name == '起点' || data.name == '终点') {} else {
			me._infoWindow.setContent(me.view.createInfowindowContent(data));
			me._infoWindow.open(me.options.map, this.getPosition());
		}

		me.options.map.setCenter(this.getPosition());
	}

	me.listener.unfocusTitleMouseenter = function(e) {
		var index = this.getAttribute("index");
		me.drawRoute(index);

		me.listener.unfocusTitleMouseenter.last = this;
	}
	me.listener.unfocusTitleMouseleave = function(e) {
		me.clearRoute();
	}

}